package com.dongnao.network.netty_packet;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.util.UUID;

public class NettyServerHandler2 extends SimpleChannelInboundHandler<MessageProtocol> {

    private int count;

    //读取数据
    @Override
    public void channelRead0(ChannelHandlerContext ctx, MessageProtocol msg) throws UnsupportedEncodingException {
        //接收到数据并处理
        int len = msg.getLen();
        byte[] content = msg.getContent();

        System.out.println("服务器接收到数据：");
        System.out.println("长度：" + len);
        System.out.println("内容：" + new String(content, Charset.forName("utf-8")));

        System.out.println("服务器接收到数量" + (++count));

        //回复消息
        String responseContent = UUID.randomUUID().toString();
        byte[] resp = responseContent.getBytes("utf-8");
        int responseLen = resp.length;
        //构建一个协议包
        MessageProtocol messageProtocol = new MessageProtocol();
        messageProtocol.setLen(responseLen);
        messageProtocol.setContent(resp);

        ctx.writeAndFlush(messageProtocol);
    }

    //异常处理
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        ctx.close();
    }

}
